<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search, Refresh, Plus, DataLine, Star, ChatDotRound, Edit, Delete } from '@element-plus/icons-vue'
import { getQAList, deleteQA, getQAStatistics, getSceneTypes } from '@/api/qa'
import type { ArticleQA, ArticleQAQuery, ArticleQAStatistics } from '@/api/types'
import { SceneType } from '@/api/types'
import { handleError } from '@/utils/error-handler'
import QADialog from './components/QADialog.vue'

// 查询条件
const queryForm = ref<ArticleQAQuery>({
  articleTitle: '',
  sceneType: undefined,
  pageNum: 1,
  pageSize: 10
})

// 分页数据
const total = ref(0)
const loading = ref(false)
const qaList = ref<ArticleQA[]>([])

// 统计数据
const statistics = ref<ArticleQAStatistics>({
  total: 0,
  inLoveCount: 0,
  pursuingCount: 0
})

// 场景类型选项
const sceneTypes = ref<SceneType[]>([SceneType.IN_LOVE, SceneType.PURSUING])

// 编辑对话框
const dialogVisible = ref(false)
const currentQA = ref<Partial<ArticleQA>>()

// 加载数据
async function loadData() {
  loading.value = true
  try {
    // 分开加载列表数据和统计数据
    const [listRes, statsRes] = await Promise.all([
      getQAList(queryForm.value),
      getQAStatistics()
    ])

    // 更新列表数据
    qaList.value = listRes.data.data.records || []
    total.value = listRes.data.data.total || 0

    // 更新统计数据
    statistics.value = statsRes.data.data
  } catch (error) {
    handleError(error)
  } finally {
    loading.value = false
  }
}

// 搜索
function handleSearch() {
  queryForm.value.pageNum = 1
  loadData()
}

// 重置
function handleReset() {
  queryForm.value = {
    articleTitle: '',
    sceneType: undefined,
    pageNum: 1,
    pageSize: 10
  }
  handleSearch()
}

// 删除
async function handleDelete(id: number) {
  try {
    await ElMessageBox.confirm('确认删除该问答对吗？', '提示', {
      type: 'warning'
    })
    await deleteQA(id)
    ElMessage.success('删除成功')
    loadData()
  } catch (error) {
    if (error !== 'cancel') {
      handleError(error)
    }
  }
}

// 分页变化
function handleSizeChange(val: number) {
  queryForm.value.pageSize = val
  loadData()
}

function handleCurrentChange(val: number) {
  queryForm.value.pageNum = val
  loadData()
}

// 编辑
function handleEdit(row: ArticleQA) {
  console.log('handleEdit clicked', row)
  currentQA.value = { ...row }
  dialogVisible.value = true
  console.log('dialogVisible:', dialogVisible.value)
}

// 新增
function handleAdd() {
  console.log('handleAdd clicked')
  currentQA.value = undefined
  dialogVisible.value = true
  console.log('dialogVisible:', dialogVisible.value)
}

// 编辑成功
function handleSuccess() {
  loadData()
  ElMessage.success('操作成功')
}

onMounted(() => {
  loadData()
})
</script>

<template>
  <div class="qa-management">

    <!-- 搜索表单 -->
    <el-card class="search-card">
      <div class="card-header">
        <el-form :model="queryForm" inline class="search-form">
          <el-form-item label="文章标题">
            <el-input
              v-model="queryForm.articleTitle"
              placeholder="请输入文章标题"
              clearable
              class="search-input"
            />
          </el-form-item>
          <el-form-item label="场景类型">
            <el-select
              v-model="queryForm.sceneType"
              placeholder="请选择场景类型"
              clearable
              class="scene-select"
            >
              <el-option
                v-for="type in sceneTypes"
                :key="type"
                :label="type === SceneType.IN_LOVE ? '热恋中' : '追求中'"
                :value="type"
              />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleSearch" class="search-btn">
              <el-icon><Search /></el-icon>搜索
            </el-button>
            <el-button @click="handleReset" class="reset-btn">
              <el-icon><Refresh /></el-icon>重置
            </el-button>
          </el-form-item>
        </el-form>
        <el-button type="success" @click="handleAdd" class="add-btn">
          <el-icon><Plus /></el-icon>新增问答
        </el-button>
      </div>
    </el-card>

    <!-- 数据表格 -->
    <el-card class="table-card">
      <el-table
        v-loading="loading"
        :data="qaList"
        border
        stripe
        highlight-current-row
        class="qa-table"
      >
        <el-table-column prop="articleTitle" label="文章标题" min-width="200" show-overflow-tooltip />
        <el-table-column prop="question" label="问题" min-width="200" show-overflow-tooltip />
        <el-table-column prop="answer" label="答案" min-width="200" show-overflow-tooltip />
        <el-table-column prop="sceneType" label="场景类型" width="120" align="center">
          <template #default="{ row }">
            <el-tag :type="row.sceneType === 'IN_LOVE' ? 'success' : 'warning'">
              {{ row.sceneType === 'IN_LOVE' ? '热恋中' : '追求中' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间" width="180" align="center" />
        <el-table-column label="操作" width="180" fixed="right" align="center">
          <template #default="{ row }">
            <el-button link type="primary" @click="handleEdit(row)" class="edit-btn">
              <el-icon><Edit /></el-icon>编辑
            </el-button>
            <el-button link type="danger" @click="handleDelete(row.id)" class="delete-btn">
              <el-icon><Delete /></el-icon>删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination">
        <el-pagination
          v-model:current-page="queryForm.pageNum"
          v-model:page-size="queryForm.pageSize"
          :total="total"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          background
        />
      </div>
    </el-card>

    <!-- 编辑对话框 -->
    <QADialog
      v-model:visible="dialogVisible"
      :data="currentQA"
      @success="handleSuccess"
    />

    <!-- 添加调试显示 -->
    <div style="display: none;">
      Dialog Visible: {{ dialogVisible }}
      Current QA: {{ currentQA }}
    </div>
  </div>
</template>

<style scoped lang="scss">
.qa-management {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: calc(100vh - 60px);

  .statistics-cards {
    margin-bottom: 24px;

    .statistics-card {
      height: 180px;
      border-radius: 8px;
      transition: all 0.3s ease;

      .card-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        padding: 16px;
        font-size: 16px;
        font-weight: 600;

        .el-icon {
          font-size: 20px;
        }
      }

      .card-body {
        height: 120px;
        display: flex;
        flex-direction: column;
        justify-content: center;
        align-items: center;
        padding: 0 16px;

        .number {
          font-size: 48px;
          font-weight: bold;
          line-height: 1.2;
          margin-bottom: 12px;
          white-space: nowrap;
        }

        .label {
          font-size: 14px;
          color: #909399;
        }
      }

      &:hover {
        transform: translateY(-4px);
        box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
      }
    }

    .total-card {
      .card-header {
        color: #409eff;
      }
      .number {
        color: #409eff;
      }
    }

    .love-card {
      .card-header {
        color: #67c23a;
      }
      .number {
        color: #67c23a;
      }
    }

    .pursue-card {
      .card-header {
        color: #e6a23c;
      }
      .number {
        color: #e6a23c;
      }
    }
  }

  .search-card {
    margin-bottom: 24px;
    border-radius: 8px;

    .search-form {
      .search-input {
        width: 240px;
      }

      .scene-select {
        width: 140px;
      }

      .search-btn {
        margin-right: 12px;
      }
    }

    .add-btn {
      padding: 9px 20px;
    }
  }

  .table-card {
    border-radius: 8px;

    .qa-table {
      margin: 16px 0;

      :deep(.el-table__header) {
        background-color: #f5f7fa;
      }

      :deep(.el-table__row) {
        transition: all 0.3s ease;

        &:hover {
          background-color: #f5f7fa;
        }
      }
    }

    .edit-btn,
    .delete-btn {
      padding: 4px 8px;

      .el-icon {
        margin-right: 4px;
      }
    }
  }

  .pagination {
    margin-top: 24px;
    display: flex;
    justify-content: flex-end;
    padding: 0 16px 16px;
  }
}

// 深度选择器样式
:deep(.el-card) {
  border: none;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
}

:deep(.el-button) {
  display: inline-flex;
  align-items: center;
  justify-content: center;
  gap: 4px;
}

:deep(.el-tag) {
  border-radius: 4px;
}
</style>
